#!/usr/bin/env bash
# Usage: swiftenv init [-] [--[no-]rehash]
# completes

set -e

if [ "$1" = "--complete" ]; then
  echo "-"
  echo "--no-rehash"
  echo "--rehash"
  echo "bash"
  echo "zsh"
  echo "fish"
  exit
fi

print=""

rehash=true

if [ -r "$SWIFTENV_ROOT/shims" ] && [[ "$(uname)" == "Darwin" ]]; then
  # Rehash takes a long time on Darwin due to mdfind

  if [ -r "$SWIFTENV_ROOT/shims/.version" ] && [ "$(cat "$SWIFTENV_ROOT/shims/.version")" == "$(swiftenv --version)" ]; then
    rehash=false
  fi
fi

for args in "$@"
do
  if [ "$args" = "-" ]; then
    print=1
    shift
  fi

  if [ "$args" = "--rehash" ]; then
    rehash=true
    shift
  fi

  if [ "$args" = "--no-rehash" ]; then
    rehash=false
    shift
  fi
done

shell="$1"
if [ -z "$shell" ]; then
  shell="$(ps c -p "$PPID" -o 'ucomm=' 2>/dev/null || true)"
  shell="${shell##-}"
  shell="${shell%% *}"
  shell="${shell:-$SHELL}"
  shell="${shell##*/}"
fi

if [ -z "$print" ]; then
  case "$shell" in
  bash )
    if [ -f "${HOME}/.bashrc" ] && [ ! -f "${HOME}/.bash_profile" ]; then
      profile='~/.bashrc'
    else
      profile='~/.bash_profile'
    fi
    ;;
  zsh )
    profile='~/.zshrc'
    ;;
  fish )
    profile='~/.config/fish/config.fish'
    ;;
  * )
    profile='your profile'
  esac

  {
    echo "# Load swiftenv automatically by appending"
    echo "# the following to your $profile:"
    echo

    case "$shell" in
    fish )
      echo 'status --is-interactive; and source (swiftenv init -|psub)'
      ;;
    * )
      echo 'eval "$(swiftenv init -)"'
      ;;
    esac
    echo

    exit 1
  } >&2

  exit 1
fi

mkdir -p "$SWIFTENV_ROOT/"{shims,versions}
case "$shell" in
fish )
  echo "set -gx PATH '${SWIFTENV_ROOT}/shims' \$PATH"
  ;;
* )
  echo 'export PATH="'${SWIFTENV_ROOT}'/shims:${PATH}"'
  ;;
esac

if $rehash; then
  echo 'command swiftenv rehash 2>/dev/null'
fi

source_root="${0%/*}/.."
completion="$source_root/completions/swiftenv.${shell}"
if [ -r "$completion" ]; then
  echo "source '$completion'"
fi
